#include <app.h>
#include <u_syscall.h>
#include <list.h>
#include <memory.h>

APP_INFO appInfo[MAX_APP_NUM] = {0};
U16 appNum = 0;

E_RET AppRegister(APP_FUNC pFunc, U08* stackAddr, U16 stackSize, U08* name, E_APP_PRI priority)
{
    if(appNum >= MAX_APP_NUM)
        return E_ERR;

    appInfo[appNum].pfunc = pFunc;
    appInfo[appNum].stackAddr = stackAddr;
    appInfo[appNum].stackSize = stackSize;
    appInfo[appNum].name = name;
    appInfo[appNum].priority = priority;
    appNum++;

    return E_OK;
}

/******************************************************************************
* 函数名称: static void TaskIdleFunc(void)
* 功能说明: 空闲任务
* 输入参数: 无
* 输出参数: 无
* 函数返回: 无
* 其它说明: 无
******************************************************************************/
#define IDLE_STACK_SIZE   512     
static U08 taskIdle_stack[IDLE_STACK_SIZE];    // 空闲任务私有栈
static void TaskIdleFunc(void)                 // 空闲任务执行函数
{
    while(1);
}

U08 AppHeap[4096] = {0xff}; // 用户程序堆区

void Delay(U32 cnt)
{
    volatile U32 cnt_t = cnt; 
    while(cnt_t--);
}

EVENT* gEvent = NULL;
static U08 TaskAStack[256] = {0xFF};
void TaskA(void)  
{
    static U32 cnt = 0;
    gEvent = EventCreat();
    while (1)
    {
        SetCursorPos(0, 10);
        print("TASK A: %d\n", cnt++);
        if(cnt%20 == 0)
            SetEvent(gEvent);
        Delay(999999);
        if(cnt > 200)
            break;
    }
    EventDestory(gEvent);
}

static U08 TaskBStack[256] = {0xFF};
void TaskB(void)  
{
    static U32 cnt = 0;
    while (1)
    {
        WaitEvent(gEvent);
        ClearEvent(gEvent);
        SetCursorPos(0, 12);
        print("TASK B: %d\n", cnt++);
        Delay(999999);
    }
}


void AppInit(void)
{
    MemInit((U08 *)&AppHeap, 4096);

    // AppRegister(TaskA, TaskAStack, 256, "TaskA", E_APP_PRI5);
    // AppRegister(TaskB, TaskBStack, 256, "TaskB", E_APP_PRI5);

    // 把应用数据放入共享内存 0xA800 处
    *((volatile U32*)0xA800) = (U32)appInfo;
    *((volatile U32*)0xA804) = appNum;
    *((volatile U32*)0xA808) = (U32)taskIdle_stack;
    *((volatile U32*)0xA80C) = IDLE_STACK_SIZE;
    *((volatile U32*)0xA810) = (U32)TaskIdleFunc;
}
